<?php

class nRouteRegex extends nRoute {
	const OPTION_REGEX   = 'regex';
	const OPTION_PATTERN = 'pattern';

	public function __construct($options) {
		parent::__construct($options);
	}

	public function match($url) {
		if (preg_match($this->getOption(self::OPTION_REGEX, ''), $url, $matches)) {
			return $matches;
		}
		else
			return null;
	}

	private static $url_params = null;
	public function url($params = array()) {
		self::$url_params = $params;
		$pattern = $this->getOption(self::OPTION_PATTERN, '');
		return preg_replace_callback('#({([^{}]*({([^{}]*)})?[^{}]*)})#', array('nRouteRegex', '_rpl'), $pattern);
	}

	static function _rpl($matches) {
		if (count($matches) == 3)
			return
				array_key_exists($matches[2], self::$url_params)
					? self::$url_params[$matches[2]]
					: '';
		else
			return
				array_key_exists($matches[4], self::$url_params)
					? strtr($matches[2], array($matches[3] => self::$url_params[$matches[4]]))
					: '';
	}

}